﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.DataVisualization.Charting;

using Wicresoft.Common;
using Wicresoft.JDPostBoard.Entity;
using System.Drawing;

public partial class Gift_StatisticList2 : BaseAuthenticationPage
{
    public string SearchDefaultText
    {
        get
        {
            return "搜索 月份";
        }
    }

    public string SearchClause
    {
        get
        {
            if (ViewState["SearchClause"] == null)
                ViewState["SearchClause"] = "1=1 and Status='" + Enum.ApplyStatusEnum.已领取.ToString() + "' and DealTime>='" + DateTime.Now.ToString("yyyy-MM-01") + "' and DealTime<'" + DateTime.Now.AddMonths(1).ToString("yyyy-MM-01") + "'";
            return ViewState["SearchClause"].ToString();
        }
        set
        {
            ViewState["SearchClause"] = value;
        }
    }

    protected DataTable DTData
    {
        get
        {
            if (ViewState["DTData"] == null)
                ViewState["DTData"] = new DataTable();
            return ViewState["DTData"] as DataTable;
        }
        set
        {
            ViewState["DTData"] = value;
        }
    }

    protected DataTable DTAllData
    {
        get
        {
            if (ViewState["DTAllData"] == null)
                ViewState["DTAllData"] = new DataTable();
            return ViewState["DTAllData"] as DataTable;
        }
        set
        {
            ViewState["DTAllData"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Wicresoft.Framework.Organization.OrganizationPublicHelper.IsUserInRole(CurrentUser.ID, new Guid(WebCommon.GetConfig("OfficeAdminID"))))
        {
            Response.Write("对不起，您无权查看此页！<br /><br />");
            Response.Write("您可以查看<a href='MyApplyList.aspx'>我的申请页面</a>");
            Response.End();
        }

        this.ShowLRLayoutButton = false;
        this.ShowUDLayoutButton = false;
        this.ShowSimpleLayoutButton = false;
        this.DefaultLayout = LayoutCode.Simple.ToString();

        this.Title = "审核统计列表";
        this.tbSearch.Attributes.Add("onfocus", string.Format("clearText(this, '{0}');", SearchDefaultText) + "WdatePicker({dateFmt:'yyyy-MM'});");
        this.tbSearch.Attributes.Add("onblur", string.Format("insertText(this, '{0}');", SearchDefaultText));
        this.tbSearch.Attributes.Add("onkeydown", "return searchClick();");

        if (!IsPostBack)
        {
            tbSearch.Text = SearchDefaultText;
            this.Order.OrderColumn = "ApplierDepartment";
            this.Order.OrderDirection = "ASC";

            BindData();
            DTAllData = DataAccess.Select(typeof(ViewGiftApply), SearchClause);
            BindChart(DTAllData);
        }

    }

    protected void Page_PreRender(object sender, EventArgs e)
    {

    }

    protected override void Pager_PageChanged(object sender, EventArgs e)
    {
        BindData();
        DTAllData = DataAccess.Select(typeof(ViewGiftApply), SearchClause);
        BindChart(DTAllData);
        base.Pager_PageChanged(sender, e);
    }

    protected override void Order_OrderChanged(object sender, EventArgs e)
    {
        BindData();
        DTAllData = DataAccess.Select(typeof(ViewGiftApply), SearchClause);
        BindChart(DTAllData);
        base.Order_OrderChanged(sender, e);
    }

    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        BindData();
        DTAllData = DataAccess.Select(typeof(ViewGiftApply), SearchClause);
        BindChart(DTAllData);
    }

    private void BindData()
    {
        int recordCount = 0;
        string orderString = this.Order.OrderDirection == "DESC" ? string.Format("{0} {1},{2}", this.Order.OrderColumn, this.Order.OrderDirection, ViewGiftApply.SQLCOL_ID) : this.Order.OrderColumn;
        DTData = DataAccess.Select(typeof(ViewGiftApply), Pager.PageIndex, Pager.PageSize, SearchClause, orderString, ref recordCount);
        Pager.RecordCount = recordCount;
        rptOrder.DataSource = DTData;
        rptOrder.DataBind();

    }

    private void BindData(string Department)
    {
        int recordCount = 0;
        string orderString = this.Order.OrderDirection == "DESC" ? string.Format("{0} {1},{2}", this.Order.OrderColumn, this.Order.OrderDirection, ViewGiftApply.SQLCOL_ID) : this.Order.OrderColumn;
        DTData = DataAccess.Select(typeof(ViewGiftApply), Pager.PageIndex, Pager.PageSize, SearchClause + " And DealerID='" + Department + "'", orderString, ref recordCount);
        Pager.RecordCount = recordCount;
        rptOrder.DataSource = DTData;
        rptOrder.DataBind();

    }

    protected void BindChart(DataTable dt)
    {
        // Add series to the chart

        //if (Chart1.Series.FindByName("My series") != null)
        //    Chart1.Series.RemoveAt(0);
        Hashtable ht = new Hashtable();
        if (dt != null)
        {
            foreach (DataRow dr in dt.Rows)
            {
                if (ht[dr["DealerID"].ToString()] == null)
                    ht[dr["DealerID"].ToString()] = 1;
                else
                    ht[dr["DealerID"].ToString()] = int.Parse(ht[dr["DealerID"].ToString()].ToString()) + 1;
            }
        }

        //Series series = Chart1.Series.Add("My series");
        Series series = Chart1.Series["总次数"];
        // Set series visual attributes
        series.ChartType = SeriesChartType.Column;

        series.ShadowOffset = 1;
        series.Font = new Font("Times New Format", 7f);
        series.BorderColor = Color.DarkGray;
        //series.CustomAttributes = "LabelStyle=Outside";

        // Set series and legend tooltips
        series.ToolTip = "#LEGENDTEXT的总次数: #VAL";
        series.LegendToolTip = "#PERCENT";
        series.PostBackValue = "#INDEX";
        series.LegendPostBackValue = "#INDEX";
        Chart1.Titles[0].Text = "审核分布图";

        //3D
        //Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;

        // Populate series data
        double[] yValues = new double[ht.Count];
        string[] xValues = new string[ht.Count];
        int Index = 0;
        foreach (DictionaryEntry de in ht)
        {
            yValues[Index] = double.Parse(de.Value.ToString());
            Wicresoft.Framework.Organization.User user = Wicresoft.Framework.Organization.OrganizationHelper.GetUserInfo(new Guid(de.Key.ToString()));
            xValues[Index] = user.DisplayName;
            Index++;
        }
        series.Points.DataBindY(yValues);

        for (int pointIndex = 0; pointIndex < series.Points.Count; pointIndex++)
        {
            series.Points[pointIndex].LegendText = xValues[pointIndex];
            series.Points[pointIndex].AxisLabel = xValues[pointIndex];
        }
    }

    protected void Chart1_Click(object sender, ImageMapEventArgs e)
    {

        BindChart(DTAllData);
        int pointIndex = int.Parse(e.PostBackValue);
        Series series = Chart1.Series["总次数"];
        if (pointIndex >= 0 && pointIndex < series.Points.Count)
        {
            series.Points[pointIndex].CustomProperties += "Exploded=true";
            BindData(series.Points[pointIndex].LegendText);
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        SearchClause = "Status='" + Enum.ApplyStatusEnum.审核通过.ToString() + "'";
        if (tbSearch.Text != string.Empty && tbSearch.Text != SearchDefaultText)
            SearchClause += string.Format(" AND DealTime>='{0}' and DealTime<'{1}'", this.tbSearch.Text + "-01", Convert.ToDateTime(this.tbSearch.Text + "-01").AddMonths(1).ToString("yyyy-MM-01"));

        //Pager.ResetPager();
        BindData();
        DTAllData = DataAccess.Select(typeof(ViewGiftApply), SearchClause);
        BindChart(DTAllData);
    }

    protected void Print_Click(object sender, EventArgs e)
    {
        if (DTAllData == null || DTAllData.Rows.Count == 0)
        {
            WebCommon.ShowMessage(this, "无数据");
            return;
        }
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "GB2312";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("马陆镇人民政府礼品审核情况月报表") + ".xls");
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Response.ContentType = "application/ms-excel";
        string body = ToExcel();
        Response.Write(body);
        Response.End();
    }

    public string ToExcel()
    {
        int month = DateTime.Now.Month;
        if (this.tbSearch.Text != "" && this.tbSearch.Text != SearchDefaultText)
            month = Convert.ToDateTime(this.tbSearch.Text + "-01").Month;

        string displayTime = WebCommon.MonthIntToChinise(month);

        string ExcelHeader = "<div   style=\"text-align:center; background-color: #006699;font-size: 15pt;color: #000000;padding: 2pt;width:100%\">马陆镇人民政府礼品审核情况月报表<br/>(" + displayTime + ")</div>";
        Hashtable ht = new Hashtable();
        int index = 1;
        foreach (DataRow dr in DTData.Rows)
        {
            if (!ht.ContainsValue(dr["GiftName"].ToString() + "|" + dr["GiftPrice"].ToString()))
            {
                ht.Add(index, dr["GiftName"].ToString() + "|" + dr["GiftPrice"].ToString());
                index++;
            }
        }

        Hashtable htDepart = new Hashtable();
        index = 1;
        foreach (DataRow dr in DTData.Rows)
        {
            if (!htDepart.ContainsValue(dr["DealerID"].ToString()))
            {
                htDepart.Add(index, dr["DealerID"].ToString());
                index++;
            }
        }

        string TableHeader = "<table border='1' style='width:100%;'><tr ><th rowspan='2'>序号</th><th rowspan='2'>审核人</th><th colspan='" + ht.Count + "'>" + month + "月审核情况</th><th rowspan='2'>金额</th><th rowspan='2'>签名</th></tr><tr>";
        string TableFooterRow = "<tr><td style='text-align:center;'>合计</td><td></td>";
        for (int i = 0; i < ht.Count; i++)
        {
            TableHeader += "<th>" + ht[i + 1].ToString().Replace("|", "<br />") + "</th>";

            DataRow[] drSelect = DTData.Select("GiftName='" + ht[i + 1].ToString().Split('|')[0] + "'");
            float Sum = 0;
            foreach (DataRow dr in drSelect)
                Sum += int.Parse(dr["GiftTotal"].ToString());
            TableFooterRow += "<td>" + Sum.ToString("N") + "</td>";
        }
        TableHeader += "</tr>";
        TableFooterRow += "<td></td><td></td></tr>";


        string TableBody = "";

        for (int i = 0; i < htDepart.Count; i++)
        {
            Wicresoft.Framework.Organization.User user = Wicresoft.Framework.Organization.OrganizationHelper.GetUserInfo(new Guid(htDepart[i + 1].ToString()));

            TableBody += "<tr><td style='text-align:center;'>" + (i + 1).ToString() + "</td><td style='text-align:center;'>" + user.DisplayName + "</td>";

            float PriceSum = 0;
            for (int k = 0; k < ht.Count; k++)
            {
                DataRow[] drSelect = DTData.Select("DealerID='" + htDepart[i + 1].ToString() + "' and GiftName='" + ht[k + 1].ToString().Split('|')[0] + "'");
                int Sum = 0;
                foreach (DataRow dr in drSelect)
                {
                    Sum += int.Parse(dr["GiftCount"].ToString());
                    PriceSum += float.Parse(dr["GiftTotal"].ToString());
                }
                TableBody += "<td>" + Sum + "</td>";
            }
            TableBody += "<td>" + PriceSum.ToString("N") + "</td><td></td></tr>";
        }


        string TableFooter = "</table>";

        return ExcelHeader + TableHeader + TableBody + TableFooterRow + TableFooter;

    }

    protected void btnAdvancedSearch_Click(object sender, EventArgs e)
    {
        SearchClause = "Status='" + Enum.ApplyStatusEnum.审核通过.ToString() + "'";

        if (this.tbStartTime.Text != "" && this.tbEndTime.Text != "")
        {
            if (Convert.ToDateTime(this.tbStartTime.Text + "-01") > Convert.ToDateTime(this.tbEndTime.Text + "-01"))
            {
                Response.Write("<script>alert('开始月份不能小于结束月份');</script>");
                return;
            }
            SearchClause += string.Format(" AND {0} >= '{1}' AND {0} < '{2}'", ViewGiftApply.SQLCOL_CONFIRMTIME, this.tbStartTime.Text + "-01", Convert.ToDateTime(this.tbEndTime.Text + "-01").AddMonths(1).ToString("yyyy-MM-01"));

        }
        else if (this.tbStartTime.Text != "")
            SearchClause += string.Format(" AND {0} >= '{1}'", ViewGiftApply.SQLCOL_CONFIRMTIME, this.tbStartTime.Text + "-01");
        else if (this.tbEndTime.Text != "")
            SearchClause += string.Format(" AND {0} < '{1}'", ViewGiftApply.SQLCOL_CONFIRMTIME, Convert.ToDateTime(this.tbEndTime.Text + "-01").AddMonths(1).ToString("yyyy-MM-01"));

        //Pager.ResetPager();
        BindData();
        DTAllData = DataAccess.Select(typeof(ViewGiftApply), SearchClause);
        BindChart(DTAllData);

    }
}
